

// 54.螺旋矩阵
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int n = matrix.size() , m = matrix[0].size();

        int top = 0 , below = n - 1 , left = 0 , right = m - 1;
        vector<int> ret;
        while(left <= right && top <= below)
        {
            // 从左往右
            for(int i = left ; i <= right ; i++)
                ret.push_back(matrix[top][i]);
            top += 1;   // 上层-1
            if(top > below) break;
            // 从上往下
            for(int i = top ; i <= below ; i++)
                ret.push_back(matrix[i][right]);
            right -= 1;
            if(left > right) break;
            // 从右往左
            for(int i = right ; i >= left ; i--)
                ret.push_back(matrix[below][i]);
            below -= 1;
            if(top > below) break;
            // 从下往上
            for(int i = below ; i >= top ; i--)
                ret.push_back(matrix[i][left]);
            left += 1;
        }
        return ret;
    }
};